package JdbcTest.Jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;

/*
模拟用户需要升序降序需求
 */
public class JdbcTest3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入降序desc,升序asc");
        String s = scanner.nextLine();
        Connection conn = null;
        Statement sta = null;
        ResultSet rs = null;
        Properties map = new Properties();
        FileInputStream fis = null;
        try {//利用io流来读取文件中数据库连接信息
            fis = new FileInputStream("src/JdbcTest/Jdbc/DatabaseFile.properties");
            map.load(fis);
            String driver = map.getProperty("Driver");
            String url = map.getProperty("url");
            String username = map.getProperty("username");
            String password = map.getProperty("password");
            //1.注册驱动
            Class c = Class.forName(driver);
            //2.获取数据库连接对象
            conn = DriverManager.getConnection(url,username,password);
            sta = conn.createStatement();
            String sql = "select * from t_user order by id "+s+"";
            rs = sta.executeQuery(sql);
            while(rs.next()){
                String id = rs.getString("id");
                String name = rs.getString("name");
                System.out.println(id+"\t"+name);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (sta != null) {
                try {
                    sta.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
